﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Threading;
using DoubleH.Utility.Configuration;
using Table=FCNS.Data.Table;
using System.Windows.Media;
using DoubleH.Utility;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
//using POS.Plugins;
using System.Data.SQLite;
using System.Reflection;

namespace POS
{
    /// <summary>
    /// xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        #region 属性 
       static bool offLine = false;
        public static bool OffLine
        {
            get { return offLine; }
            set { OffLine = value; }
        }
        /// <summary>
        /// 系统所有可用的模板
        /// </summary>
        public static List<TempleteDefine> AllTemplete { get { return window.AllTemplete; } set { window.AllTemplete = value; } }

        //static Brush backgroundBrush = Brushes.Black;
        public static Brush BackgroundBrush
        {
            get;
            set;
        }

        //static Brush foregroundBrush = Brushes.White;
        public static Brush ForegroundBrush
        {
            get;
            set;
        }

        static EnumMode mode = EnumMode.零售模式;
        /// <summary>
        /// 销售模式、退货模式
        /// </summary>
        public static EnumMode Mode
        {
            get { return mode; }
            set { mode = value; }
        }
        /// <summary>
        /// 当前班次
        /// </summary>
        public static Table.PosShiftS CurrentShift { get; set; }

        static Table.PosOrderS order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
        /// <summary>
        /// 当前操作中的订单
        /// </summary>
        public static Table.PosOrderS Order
        {
            get { return order; }
            set
            {
                order = value;
            }
        }

        /// <summary>
        /// 当前POS机的实例
        /// </summary>
        public static Table.PosS Pos
        {
            get;
            set;
        }

        static Table.CorS vip = null;
        /// <summary>
        /// 当前订单的Vip,只能通过GetVip赋值
        /// </summary>
        public static Table.CorS Vip
        {
            get
            { return vip; }
            private set
            {
                vip = value;
                foreach (Table.ProductS ps in App.order.ProductSList.Where(f => f._Tag == null))
                    ps.InitPrice(value);
            }
        }

        #endregion 

        /// <summary>
        /// 更改支付方式
        /// </summary>
        public static void ChangedPayMode()
        {
            if (mode == EnumMode.零售模式)
                window.ChangedPayMode();
            else
                MessageWindow.Show("非零售模式不可更改支付方式.");
        }

        /// <summary>
        /// 搜索商品并弹出商品选择框
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static Table.ProductS GetProductSBySearch(string text)
        {
            Table.ProductS product = null;
            var vr = Table.ProductS.GetListForPos(App.Pos.StoreSId, text);
            if (vr != null && vr.Count > 0)
            {
                if (vr.Count == 1)
                    product = vr[0];
                else
                {
                    SelectObject sp = new SelectObject();
                    sp.Owner = Application.Current.MainWindow;
                    sp.Init(SelectObject.EnumType.商品, vr);
                    sp.ShowDialog();
                    product = sp.Product;
                }
            }

            if (product == null)
                return null;
            else
            {
                product.InitPrice(null);
                return product;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="searchInGuaDan">true 通过App.Order.CorSId 查找唯一值</param>
        /// <param name="onlyVip">true  仅搜索Vip用户</param>
        /// <returns></returns>
        public static Table.CorS GetCorSBySearch(string searchText, bool searchInGuaDan, bool onlyVip)
        {
            Table.CorS corS = null;
            if (searchInGuaDan)
                corS = Table.CorS.GetObject(App.order.CorSId);
            else
            {
                var vr = (onlyVip ? Table.CorS.GetVipList(searchText, false) : Table.CorS.GetList(searchText, Table.CorS.EnumEnable.启用, Table.CorS.EnumFlag.客户, Table.CorS.EnumFlag.客户和供应商));
                if (vr != null && vr.Count > 0)
                {
                    if (vr.Count == 1)
                        corS = vr[0];
                    else
                    {
                        SelectObject so = new SelectObject();
                        so.Init(SelectObject.EnumType.会员, vr);
                        so.ShowDialog();
                        corS = so.CorS;
                    }
                }
            }

            if (!searchInGuaDan)
            {
                if (corS == null)
                    MessageWindow.Show("会员不存在");
                else if (corS.VipDateEnd < DateTime.Now)
                    MessageWindow.Show("会员已过期");
            }
            App.Vip = corS;

            return corS;
        }

        public static void Close()
        {
            window.CloseThis();
        }

        public static void LogOff(bool confirm)
        {
            window.LogOff(confirm);
        }

        public static void SysConfig()
        {
            if (Table.UserS.LoginUser == null)
                return;
            if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.POS机配置) > Table.UserS.EnumAuthority.无权限)
            {
                WindowConfig wc = new WindowConfig();
                wc.Init();
                wc.ShowDialog();
            }
            else
                MessageWindow.Show("权限不足");
        }

        static DoubleH.Utility.IO.PosLed posLed = null;
        /// <summary>
        /// 开启 顾客屏幕
        /// </summary>
        public static void OpenLed()
        {
            if (posLed != null)
            {
                posLed.Open();
                posLed.Sum(App.Order.Money.ToString());
            }
        }
        /// <summary>
        /// 顾客屏幕 显示金额 并关闭 顾客屏幕
        /// </summary>
        /// <param name="allMoney"></param>
        /// <param name="changeMoney"></param>
        public static void ShowLed(string allMoney, string changeMoney)
        {
            if (posLed == null)
                return;

            posLed.Get(allMoney);
            posLed.OddChange(changeMoney);
            posLed.Close();
        }

        static MainWindow window;
        DataConfig dataConfig;
        protected override void OnStartup(StartupEventArgs e)
        {
            if (System.Diagnostics.Process.GetProcessesByName("POS").Length > 1)
            {
                MessageBox.Show("当前程序已运行");
                Environment.Exit(0);
            }

            InitDatabase();
            CheckIsUsePOS();
            LoadDataExchange();
            InitHardware();

            window = new MainWindow();
            window.Init();
            window.Show();
        }

        private void InitDatabase()
        {
            //先验证配置文件
            dataConfig = DoubleHConfig.AppConfig.DataConfigItems.FirstOrDefault(f => { return f.Flag == DoubleHConfig.AppConfig.DataFlag; });
            if (dataConfig == null)
            {
                if (DoubleH.Utility.Login.LoginUtility.ShowLoginWindowSuccess(Table.UserS.EnumFlag.操作员))
                    dataConfig = DoubleHConfig.AppConfig.DataConfigItems.FirstOrDefault(f => { return f.Flag == DoubleHConfig.AppConfig.DataFlag; });
            }
            if (dataConfig == null)
            {
                MessageWindow.Show("数据库配置错误");
                System.Environment.Exit(0);
            }

            Debug.Assert(dataConfig != null);
            bool conServer = DoubleH.Utility.Net.NetUtility.TestConnection(dataConfig);
            if (string.IsNullOrEmpty(DoubleHConfig.AppConfig.PosNO))//如果机器标识为空就必须先联网确认了
                DoubleHConfig.AppConfig.PosOfflineMode = 0;

            switch (DoubleHConfig.AppConfig.PosOfflineMode)
            {
                case 0:
                    if (!conServer)
                    {
                        MessageWindow.Show("数据库连接失败,请检查数据库配置信息或增大超时值再尝试.");
                        Environment.Exit(0);
                    }
                    else
                        FCNS.Data.SQLdata.SqlConfig = new FCNS.Data.SQLdata.SqlString((FCNS.Data.DataType)Enum.Parse(typeof(FCNS.Data.DataType), dataConfig.DataType), dataConfig.DataAddress, dataConfig.DataName,
                                  dataConfig.Port, dataConfig.DataUser, dataConfig.DataPassword, dataConfig.TimeOut, dataConfig.HttpPort);
                    break;

                case 1:
                    if (!conServer)
                        goto case 2;
                    else
                        try
                        {
                            FCNS.Data.SQLdata.SqlConfig = new FCNS.Data.SQLdata.SqlString((FCNS.Data.DataType)Enum.Parse(typeof(FCNS.Data.DataType), dataConfig.DataType), dataConfig.DataAddress, dataConfig.DataName,
                               dataConfig.Port, dataConfig.DataUser, dataConfig.DataPassword, dataConfig.TimeOut, dataConfig.HttpPort);
                        }
                        catch
                        {
                            goto case 2;
                        }
                    break;

                case 2:
                    FCNS.Data.SQLdata.SqlConfig = new FCNS.Data.SQLdata.SqlString(FCNS.Data.DataType.SQLITE, string.Empty, FCNS.Data.DbDefine.dbFile, 0, null, null, 0, 80);
                    offLine = true;
                    break;
            }
        }

        private void CheckIsUsePOS()
        {
            if (!Table.SysConfig.SysConfigParams.UsePos)
            {
                MessageWindow.Show("POS零售 未启用");
                System.Environment.Exit(0);
            }
        }

        private void LoadDataExchange()
        {
            if (Table.SysConfig.SysConfigParams.PosOfflineMode==0)
                return;

            Process[] pro = Process.GetProcessesByName("DataExchange");
            if (pro.Length != 0)
                return;

            string file = FCNS.Data.DbDefine.baseDir + "DataExchange.exe";
            if (!System.IO.File.Exists(file))
            {
                MessageWindow.Show("数据交换器丢失,请修复.");
                return;
            }

            Process.Start(file);
        }

        private void InitHardware()
        {
            if (!string.IsNullOrEmpty(DoubleHConfig.AppConfig.PosLed) && DoubleHConfig.AppConfig.PosLed != "无")
                posLed = new DoubleH.Utility.IO.PosLed();
        }
    }

    /// <summary>
    /// 定义模板的信息
    /// </summary>
    public class TempleteDefine
    {
        /// <summary>
        /// 文本标识
        /// </summary>
        public string Text { get; set; }
        /// <summary>
        /// 文件名标识
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 店铺类型
        /// </summary>
        public Table.PosS.EnumFlag PosFlag { get; set; }
        /// <summary>
        /// 是否触摸屏？如果是 键盘快捷键就禁止。
        /// </summary>
        public bool IsTouch { get; set; }
    }

    #region 枚举
    //public enum PosType
    //{
    //    零售店=0,
    //    酒吧
    //}

    public enum EnumProductSMode
    {
        按销量排行 = 0,
        自定义
    }
    public enum EnumUI
    {
        登陆,
        零售,
        结账
    }
    public enum EnumMode
    {
        //练习模式=0,
        零售模式,
        退货模式
    }
    #endregion
}